package com.buybuyyi.stylistcrm.order.service.impl;


import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.buybuyyi.stylistcrm.consts.DateFormatPattern;
import com.buybuyyi.stylistcrm.order.dao.InvoiceOrderDao;
import com.buybuyyi.stylistcrm.order.dao.InvoiceOrderGoodsDao;
import com.buybuyyi.stylistcrm.order.dao.PurchaseOrderGoodsDao;
import com.buybuyyi.stylistcrm.order.dao.TransferOrderGoodsDao;
import com.buybuyyi.stylistcrm.order.po.*;
import com.buybuyyi.stylistcrm.utils.DateUtil;
import com.buybuyyi.stylistcrm.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import stylistcrm.core.query.ResultPagerModel;
import stylistcrm.core.services.goods.dto.GoodsYardageDTO;
import stylistcrm.core.services.goods.dto.GoodsYardageDelDTO;
import stylistcrm.core.services.goods.service.IGoodsForeignService;
import stylistcrm.core.services.order.dto.*;
import stylistcrm.core.services.order.enums.EnumExceptionCode;
import stylistcrm.core.services.order.enums.EnumOrderType;
import stylistcrm.core.services.order.exception.BizException;
import stylistcrm.core.services.order.service.InvoiceOrderService;


@Service
public class InvoiceOrderServiceImpl implements InvoiceOrderService {

	@Autowired
	private InvoiceOrderDao invoiceOrderDao;

	@Autowired
	private InvoiceOrderGoodsDao invoiceOrderGoodsDao;

	@Autowired
	private PurchaseOrderGoodsDao purchaseOrderGoodsDao;

	@Autowired
	private TransferOrderGoodsDao transferOrderGoodsDao;

	/*@Autowired
	private IGoodsForeignService goodsService;*/
	/**
	 * 创建发货单
	 */
	@Override
	@Transactional
	public Boolean createInvoiceOrder(Integer currentUserId,InvoiceOrderDto invoiceOrderDto) throws BizException {
		//校验参数不为空
		if(null == invoiceOrderDto){
			throw new BizException(EnumExceptionCode.EC0001);
		}
		//收货地址不存在
		if(null == invoiceOrderDto.getConsigneeId()){
			throw new BizException(EnumExceptionCode.EC0002);
		}
		//设置收货地址
		setInvoiceGoodsList(invoiceOrderDto);
		//dto转换为entity保存入库
		InvoiceOrder order=convertDto2Entity(invoiceOrderDto);
		if(null!=order){
			//保存订单
			Integer ret=invoiceOrderDao.insertSelective(order);
			if(ret>0){
				//获取商品信息
				List<InvoiceOrderGoodsDto> goodsList=invoiceOrderDto.getGoods();
				if(goodsList==null||goodsList.isEmpty()){
					return Boolean.TRUE;
				}
				Map<Integer,GoodsYardageDelDTO> goodsDTOMap=new HashMap<>();
				for(InvoiceOrderGoodsDto goods:goodsList){
					InvoiceOrderGoods orderGoods=convertDto2Entity(goods);
					if(null==orderGoods){
						continue;
					}
					orderGoods.setInvoiceOrderId(order.getId());
					//保存商品信息
					invoiceOrderGoodsDao.insertSelective(orderGoods);
					//更新订单发货数量
					updateOrderGoodsCount(goods);
					//扣减库存
					if(goodsDTOMap.containsKey(goods.getGoodsId())){
						GoodsYardageDTO yardageDTO=new GoodsYardageDTO();
						yardageDTO.setGoodsId(goods.getGoodsId().longValue());
						yardageDTO.setColor(goods.getColor());
						yardageDTO.setSize(goods.getSize());
						yardageDTO.setStockQuantity(goods.getOrderDeliveredCount());
						goodsDTOMap.get(goods.getGoodsId()).getYardageDtos().add(yardageDTO);
					}else{
						GoodsYardageDelDTO goodsYardageDto=new GoodsYardageDelDTO();
						goodsYardageDto.setGoodsId(goods.getGoodsId().longValue());
						goodsYardageDto.setOperatingId(currentUserId.longValue());
						List<GoodsYardageDTO> yardageDTOList=new ArrayList<>();
						GoodsYardageDTO yardageDTO=new GoodsYardageDTO();
						yardageDTO.setGoodsId(goods.getGoodsId().longValue());
						yardageDTO.setColor(goods.getColor());
						yardageDTO.setSize(goods.getSize());
						yardageDTO.setStockQuantity(goods.getOrderDeliveredCount());
						yardageDTOList.add(yardageDTO);
						goodsYardageDto.setYardageDtos(yardageDTOList);
						goodsDTOMap.put(goods.getGoodsId(),goodsYardageDto);
					}
				}
				if(goodsDTOMap!=null&&!goodsDTOMap.isEmpty()){
					List<GoodsYardageDelDTO> changeYardageList= new ArrayList<>(goodsDTOMap.values());
					if(changeYardageList!=null&&!changeYardageList.isEmpty()){
						//goodsService.DeductionsGoodsYardage(changeYardageList);
					}
				}
			}
		}
		return Boolean.TRUE;
	}

	/**
	 * 发货完成，修改原有订单中的商品数量
	 * @param goods
	 * @throws BizException
     */
	private void updateOrderGoodsCount(InvoiceOrderGoodsDto goods) throws BizException {
		if(goods==null){
			return;
		}
		//进货单修改发货数量
		if(EnumOrderType.PURCHASE_ORDER.getCode().equals(goods.getOrderType())){
			PurchaseOrderGoods purchaseOrderGoods=purchaseOrderGoodsDao.selectByPrimaryKey(goods.getOrderId());
			if(null==purchaseOrderGoods){
				throw new BizException(EnumExceptionCode.EC0007);
			}
			Integer deliveredCount=(purchaseOrderGoods.getDeliveredCount()==null?0:purchaseOrderGoods.getDeliveredCount())+goods.getOrderDeliveredCount();
			purchaseOrderGoods.setDeliveredCount(deliveredCount);
			purchaseOrderGoods.setModifyTime(new Date());
			purchaseOrderGoodsDao.updateByPrimaryKey(purchaseOrderGoods);
		}else if(EnumOrderType.TRANSFER_ORDER.getCode().equals(goods.getOrderType())){
			//调货单修改发货数量
			TransferOrderGoods transferOrderGoods=transferOrderGoodsDao.selectByPrimaryKey(goods.getOrderId());
			if(null==transferOrderGoods){
				throw new BizException(EnumExceptionCode.EC0007);
			}
			Integer deliveredCount=(transferOrderGoods.getDeliveredCount()==null?0:transferOrderGoods.getDeliveredCount())+goods.getOrderDeliveredCount();
			transferOrderGoods.setDeliveredCount(deliveredCount);
			transferOrderGoods.setModifyTime(new Date());
			transferOrderGoodsDao.updateByPrimaryKey(transferOrderGoods);
		}
	}
	/**
	 * 将字符串转换为对象
	 * @param invoiceOrderDto
     */
	private void setInvoiceGoodsList(InvoiceOrderDto invoiceOrderDto){
		if(null==invoiceOrderDto){
			return;
		}
		String goodsListStr=invoiceOrderDto.getGoodsList();
		if(StringUtil.isBlank(goodsListStr)){
			return;
		}
		//将商品信息字符串转换为对象
		List<InvoiceOrderGoodsDto> goodsList=JSONArray.parseArray(goodsListStr,InvoiceOrderGoodsDto.class);
		if(null!=goodsList){
			invoiceOrderDto.setGoods(goodsList);
		}
	}
	/**
	 *
	 * @描述：将进货单dto转换为entity
	 * @param invoiceOrderDto
	 * @return
	 * @return PurchaseOrder
	 * @exception
	 * @createTime：2016年8月31日
	 * @author: chenyong
	 */
	private InvoiceOrder convertDto2Entity(InvoiceOrderDto invoiceOrderDto){
		if(null == invoiceOrderDto){
			return null;
		}
		InvoiceOrder order=new InvoiceOrder();
		order.setStatus(invoiceOrderDto.getStatus());
		order.setExpressCode(invoiceOrderDto.getExpressCode());
		order.setConsignerId(invoiceOrderDto.getConsignerId());
		order.setConsignerName(invoiceOrderDto.getConsignerName());
		order.setConsignerTelphone(invoiceOrderDto.getConsignerTelphone());
		if(StringUtil.isNotBlank(invoiceOrderDto.getCreateTime())){
			order.setCreateTime(DateUtil.parseDate(invoiceOrderDto.getCreateTime(), DateFormatPattern.PATTERN_YYYY_MM_DD_HHMMSS));
		}else{
			order.setCreateTime(new Date());
		}
		if(StringUtil.isNotBlank(invoiceOrderDto.getDeliveryTime())){
			order.setDeliveryTime(DateUtil.parseDate(invoiceOrderDto.getDeliveryTime(), DateFormatPattern.PATTERN_YYYY_MM_DD_HHMMSS));
		}else{
			order.setDeliveryTime(new Date());
		}
		order.setDeliveryWay(Integer.parseInt(invoiceOrderDto.getDeliveryWay()));
		order.setDesignerId(invoiceOrderDto.getDesignerId());
		order.setConsigneeId(invoiceOrderDto.getConsigneeId());
		if(StringUtil.isNotBlank(invoiceOrderDto.getModifyTime())){
			order.setModifyTime(DateUtil.parseDate(invoiceOrderDto.getModifyTime(), DateFormatPattern.PATTERN_YYYY_MM_DD_HHMMSS));
		}
		return order;
	}
	/**
	 *
	 * @描述：将进货单商品dto转换为entity
	 * @param goodsDto
	 * @return
	 * @return PurchaseOrderGoods
	 * @exception
	 * @createTime：2016年8月31日
	 * @author: chenyong
	 */
	private InvoiceOrderGoods convertDto2Entity(InvoiceOrderGoodsDto goodsDto){
		if(null==goodsDto){
			return null;
		}
		InvoiceOrderGoods orderGoods=new InvoiceOrderGoods();
		orderGoods.setOrderGoodsId(goodsDto.getOrderId());
		if(StringUtil.isNotBlank(goodsDto.getCreateTime())){
			orderGoods.setCreateTime(DateUtil.parseDate(goodsDto.getCreateTime(), DateFormatPattern.PATTERN_YYYY_MM_DD_HHMMSS));
		}else{
			orderGoods.setCreateTime(new Date());
		}
		if(StringUtil.isNotBlank(goodsDto.getModifyTime())){
			orderGoods.setModifyTime(DateUtil.parseDate(goodsDto.getModifyTime(),DateFormatPattern.PATTERN_YYYY_MM_DD_HHMMSS));
		}
		orderGoods.setDeliveredCount(goodsDto.getOrderDeliveredCount());
		orderGoods.setGoodsColor(goodsDto.getColor());
		orderGoods.setGoodsSize(goodsDto.getSize());
		orderGoods.setGoodsId(goodsDto.getGoodsId());
		orderGoods.setGoodsName(goodsDto.getGoodsName());
		orderGoods.setGoodsBuyingPrice(goodsDto.getGoodsBuyingPrice());
		orderGoods.setGoodsSalePrice(goodsDto.getGoodsSalePrice());
		orderGoods.setGoodsTagPrice(goodsDto.getGoodsTagPrice());
		orderGoods.setOrderPrice(goodsDto.getOrderPrice());
		orderGoods.setTotalPrice(goodsDto.getTotalPrice());
		orderGoods.setOrderType(goodsDto.getOrderType());
		orderGoods.setYardageId(goodsDto.getYardageId());
		return orderGoods;
	}
	
	/**
	 * 分页查询发货单
	 */
	@Override
	public ResultPagerModel<InvoiceOrderDto> getPageList(QueryOrderConditionDto queryCondition) {
		Integer currentPage=queryCondition.getCurrentPage();
		Integer pageSize=queryCondition.getPageSize();
		if(currentPage==null){
			currentPage=1;
			queryCondition.setCurrentPage(currentPage);
		}
		if(pageSize==null){
			pageSize=15;
			queryCondition.setPageSize(pageSize);
		}
		queryCondition.setStart((currentPage-1)*pageSize);
		//根据查询条件查询主键（由于商品名称存在多表中，按商品名称查询订单先查订单主键）
		List<Integer> ids=this.getPageIdList(queryCondition);

		ResultPagerModel<InvoiceOrderDto> resultPager=new ResultPagerModel<InvoiceOrderDto>();
		resultPager.setCurrentPage(currentPage);
		resultPager.setPageSize(pageSize);
		List<InvoiceOrderDto> invoiceOrderList=new ArrayList<>();
		//为空返回空集合
		if(ids==null||ids.isEmpty()){
			resultPager.setTotalServerItems(0);
		}else{
			queryCondition.setIds(ids);
			invoiceOrderList=invoiceOrderDao.getPageList(queryCondition);
			Integer totalCount=this.getTotalCount(queryCondition);
			resultPager.setTotalServerItems(totalCount);
		}
		resultPager.setData(invoiceOrderList);
		return resultPager;
	}

	/**
	 * 通过主键查询发货单
	 * @param id
	 * @return
     */
	@Override
	public InvoiceOrderDto selectByPrimaryKey(Integer id) {
		QueryOrderConditionDto queryCondition=new QueryOrderConditionDto();
		List<Integer> ids=new ArrayList<Integer>();
		ids.add(id);
		queryCondition.setIds(ids);
		List<InvoiceOrderDto> invoiceOrderList=invoiceOrderDao.getPageList(queryCondition);
		if(null!=invoiceOrderList&&0!=invoiceOrderList.size()){
			return invoiceOrderList.get(0);
		}
		return null;
	}

	/**
	 * 根据条件查询发货单主键
	 * @param queryCondition
	 * @return
     */
	@Override
	public List<Integer> getPageIdList(QueryOrderConditionDto queryCondition) {
		return invoiceOrderDao.getPageIdList(queryCondition);
	}

	/**
	 * 查询总的发货单数量
	 * @param queryCondition
	 * @return
     */
	@Override
	public Integer getTotalCount(QueryOrderConditionDto queryCondition) {
		return invoiceOrderDao.getTotalCount(queryCondition);
	}

}
